package com.zhongde.cloud89app.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.android.tu.loadingdialog.LoadingDailog;
import com.bin.david.form.core.SmartTable;
import com.bin.david.form.core.TableConfig;
import com.bin.david.form.data.CellInfo;
import com.bin.david.form.data.column.Column;
import com.bin.david.form.data.format.bg.BaseCellBackgroundFormat;
import com.bin.david.form.data.format.bg.IBackgroundFormat;
import com.bin.david.form.data.format.bg.ICellBackgroundFormat;
import com.bin.david.form.data.style.FontStyle;
import com.bin.david.form.data.table.TableData;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhongde.cloud89app.MainActivity;
import com.zhongde.cloud89app.R;
import com.zhongde.cloud89app.bean.MeterData;
import com.zhongde.cloud89app.utils.MyPreference;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.OkHttpClient;

import static com.zhongde.cloud89app.base.Configuration.BASE_URL;

public class DataInfoActivity extends AppCompatActivity {

    private EditText searchtext;
    private Button searchbtn, listtime, listerror;
    private SmartTable<MeterData> smartTable;
    private List<MeterData> meterDataList = new ArrayList<>();
    private RefreshLayout smartRefreshLayout;
    private int page = 1;
    boolean first = true;
    private RelativeLayout searchview;
    private Button choose_wheel;
    private String menuname;
    private int wheelAll = 0;
    private String selectWheel = "";
    private String[] split;
    private int order = 1;
    private ImageButton zoom;
    private LoadingDailog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_info);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        initSmartTable();
        menuname = getIntent().getStringExtra("menuname");
        actionBar.setTitle(menuname);
        smartRefreshLayout = findViewById(R.id.refreshLayout);
        choose_wheel = findViewById(R.id.choose_wheel);
        searchtext = findViewById(R.id.searchtext);
        searchbtn = findViewById(R.id.searchbtn);
        listtime = findViewById(R.id.listtime);
        listerror = findViewById(R.id.listerror);
        searchview = findViewById(R.id.searchview);
        zoom = findViewById(R.id.zoom);
        LoadingDailog.Builder loadBuilder = new LoadingDailog.Builder(this)
                .setMessage("登录中...")
                .setCancelable(false)
                .setCancelOutside(false);
        dialog = loadBuilder.create();
        initData();
        initWheel();
        TableConfig tableConfig = smartTable.getConfig();
        tableConfig.setShowXSequence(false);


        smartRefreshLayout.setRefreshHeader(new ClassicsHeader(this).setSpinnerStyle(SpinnerStyle.Scale));
        smartRefreshLayout.setRefreshFooter(new ClassicsFooter(this).setSpinnerStyle(SpinnerStyle.Scale));
        smartRefreshLayout.setEnableRefresh(true);
        smartRefreshLayout.setOnLoadMoreListener(refreshLayout -> {
            initData();
        });

        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                page = 1;
                first = true;
                initData();

            }
        });

        zoom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {//判断是否为竖屏
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                } else {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }


            }
        });

        listtime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                first = true;
                order = 2;
                page = 1;
                initData();
            }
        });

        listerror.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                first = true;
                order = 1;
                page = 1;
                initData();
            }
        });

        searchbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = searchtext.getText().toString().trim();
                if (content.isEmpty()) return;
                //查询表号
                table_number_select(content);
            }
        });

        //设置轮次
        choose_wheel.setOnClickListener(v -> {
            String[] wheels = new String[wheelAll];
            boolean[] check_wheels = new boolean[wheelAll];
            List<String> checks = new ArrayList<>();

            if (split.length == 0) {
                Toast.makeText(this, "暂无数据", Toast.LENGTH_SHORT).show();
                return;
            }

            for (int i = 0; i < split.length; i++) {
                checks.add(split[i]);
            }

            for (int i = 0; i < wheelAll; i++) {
                wheels[i] = "第" + (i + 1) + "轮";
                check_wheels[i] = false;
            }
            for (int i = 0; i < split.length; i++) {
                check_wheels[Integer.valueOf(split[i].trim()) - 1] = true;
            }
            dialogMoreChoice(wheels, check_wheels, checks);
        });
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        if (newConfig.orientation == 2) {

            searchview.setVisibility(View.GONE);
        } else {
            searchview.setVisibility(View.VISIBLE);
        }


    }


    //查询表号
    private void table_number_select(String content) {

        OkHttpUtils
                .post()
                .url(BASE_URL + "Z_f_menuname_data_Controller/table_number_select.do")
                .addParams("menuname", menuname)
                .addParams("meterCoding", content)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(DataInfoActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {

                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(response);

                            JSONArray jsonArray = jsonObject.getJSONArray("data");

                            if (jsonArray.length() > 0) {
                                List<MeterData> meterDataLists = new ArrayList<>();
                                Gson gson = new Gson();
                                meterDataLists = gson.fromJson(jsonArray.toString(), new TypeToken<List<MeterData>>() {
                                }.getType());

                                meterDataLists.stream().forEach(meterData -> {

                                    if (meterData.getFinishTime() != null) {
                                        String aa = meterData.getFinishTime().replace("</font>", "");
                                        String bb = aa.replace("<font color='red' >", "");
                                        Log.e("data", bb);
                                        meterData.setFinishTime(bb);
                                    }
                                    if (meterData.getAnalysisResult() != null) {
                                        String aa = meterData.getAnalysisResult().replace("</font>", "");
                                        String bb = aa.replace("<font color='red'>", "");
                                        Log.e("data", bb);
                                        meterData.setAnalysisResult(bb);
                                    }

                                    switch (meterData.getReadingState()) {
                                        case "0":
                                            meterData.setReadingState("未采集");
                                            break;
                                        case "1":
                                            meterData.setReadingState("正在采集");
                                            break;
                                        case "2":
                                            meterData.setReadingState("采集完成");
                                            break;
                                        case "3":
                                            meterData.setReadingState("采集失败");
                                            break;
                                    }

                                });
                                smartTable.setData(meterDataLists);

                            } else {
                                Toast.makeText(DataInfoActivity.this, "查无结果", Toast.LENGTH_SHORT)
                                        .show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onAfter(int id) {
                        super.onAfter(id);
                        dialog.dismiss();
                    }
                });


    }

    /**
     * 多选
     */
    private void dialogMoreChoice(String[] items, boolean[] check_wheels, List<String> checks) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this, 0);
        builder.setTitle("选择轮次");
        builder.setMultiChoiceItems(items, check_wheels,
                (dialog, which, isChecked) -> {
                    which = which + 1;
                    if (isChecked) {
                        if (!checks.contains("" + which))
                            checks.add(which + "");
                    } else {
                        if (checks.contains("" + which)) {
                            checks.remove(checks.indexOf(which + ""));
                        }
                    }
                });
        builder.setPositiveButton("确定", (dialog, which) -> {
            dialog.dismiss();
            Toast.makeText(DataInfoActivity.this, "确定", Toast.LENGTH_SHORT)
                    .show();
            changeWheel(checks);
        });
        builder.setNegativeButton("取消", null);
        builder.create().show();
    }


    private void changeWheel(List<String> wheelInteger) {
        dialog.show();
        Map<String, String> params = new IdentityHashMap<>();
        wheelInteger.stream().forEach(s -> params.put(new String("wheel_integer"), s));
        params.put("menuname", menuname);
        OkHttpUtils
                .post()
                .url(BASE_URL + "AppcallingInterface_Controller/update_wheel_by_menuname.do")
                .params(params)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(DataInfoActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {

                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.getInt("code") == 0) {
                                page = 1;
                                first = true;
                                initData();
                                initWheel();
                            }
                            Toast.makeText(DataInfoActivity.this, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        Log.e("TAG", response);
                    }

                    @Override
                    public void onAfter(int id) {
                        super.onAfter(id);
                        dialog.dismiss();
                    }
                });


    }


    private void initWheel() {
        dialog.show();
        OkHttpUtils
                .post()
                .url(BASE_URL + "AppcallingInterface_Controller/selected_wheel_by_menuname.do")
                .addParams("menuname", menuname)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(DataInfoActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {

                        try {
                            JSONObject jsonObject = new JSONObject(response).getJSONObject("data");
                            wheelAll = jsonObject.getInt("wheelAll");
                            selectWheel = jsonObject.getString("selectWheel");
                            split = selectWheel.split(",");

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onAfter(int id) {
                        super.onAfter(id);
                        dialog.dismiss();
                    }
                });


    }

    //初始化表格
    private void initSmartTable() {
        smartTable = (SmartTable<MeterData>) findViewById(R.id.smart_table);
        smartTable.getConfig().setShowTableTitle(true);
        smartTable.getConfig().setColumnTitleStyle(new FontStyle(50, Color.BLACK));
        smartTable.getConfig().setShowXSequence(true);
        smartTable.getConfig().setShowYSequence(true);
        smartTable.setZoom(true, 2, 0.2f);
        smartTable.getConfig().setContentCellBackgroundFormat(new BaseCellBackgroundFormat<CellInfo>() {
            @Override
            public int getBackGroundColor(CellInfo cellInfo) {
                int color = R.color.white;
                if (cellInfo.col == 1) {
                    switch (cellInfo.value) {
                        case "★":
                            color = R.color.yellow;
                            break;
                        case "★★":
                            color = R.color.orange;
                            break;
                        case "★★★":
                            color = R.color.red;
                            break;
                        default:
                            color = R.color.white;
                            break;
                    }
                }
                return ContextCompat.getColor(DataInfoActivity.this, color);
            }

        });
    }

    private void initData() {
        dialog.show();
        OkHttpUtils
                .post()
                .url(BASE_URL + "AppcallingInterface_Controller/Data_collection_select.do")
                .addParams("menuname", menuname)
                .addParams("order", order + "")
                .addParams("curPage", page + "")
                .addParams("pageSize", "300")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(DataInfoActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.getInt("code") == 1) {

                                int count = jsonObject.getInt("count");
                                if (count >= page) {
                                    page++;
                                } else {
                                    smartRefreshLayout.finishLoadMore();
                                    Toast.makeText(DataInfoActivity.this, "没有更多数据", Toast.LENGTH_SHORT).show();
                                    return;
                                }


                                JSONArray jsonArray = jsonObject.getJSONArray("data");
                                if (jsonArray.length() > 0) {
                                    List<MeterData> meterDataLists = new ArrayList<>();
                                    Gson gson = new Gson();
                                    meterDataLists = gson.fromJson(jsonArray.toString(), new TypeToken<List<MeterData>>() {
                                    }.getType());


                                    meterDataLists.stream().forEach(meterData -> {

                                        if (meterData.getFinishTime() != null) {
                                            String aa = meterData.getFinishTime().replace("</font>", "");
                                            String bb = aa.replace("<font color='red' >", "");
                                            Log.e("data", bb);
                                            meterData.setFinishTime(bb);
                                        }
                                        if (meterData.getAnalysisResult() != null) {
                                            String aa = meterData.getAnalysisResult().replace("</font>", "");
                                            String bb = aa.replace("<font color='red'>", "");
                                            Log.e("data", bb);
                                            meterData.setAnalysisResult(bb);
                                        }

                                        if (meterData.getOutageRecord() != null) {
                                            String aa = meterData.getOutageRecord().replace("</font>", "");
                                            String bb = aa.replace("<font color='red'>", "");
                                            Log.e("data", bb);
                                            meterData.setOutageRecord(bb);
                                        }


                                        switch (meterData.getReadingState()) {
                                            case "0":
                                                meterData.setReadingState("未采集");
                                                break;
                                            case "1":
                                                meterData.setReadingState("正在采集");
                                                break;
                                            case "2":
                                                meterData.setReadingState("采集完成");
                                                break;
                                            case "3":
                                                meterData.setReadingState("采集失败");
                                                break;
                                        }

                                        switch (meterData.getMeterType()) {
                                            case "0":
                                                meterData.setMeterType("?");
                                                break;
                                            case "1":
                                                meterData.setMeterType("┃");
                                                break;
                                            case "3":
                                                meterData.setMeterType("┃┃┃");
                                                break;
                                        }

                                        switch (meterData.getAnalysis()) {
                                            case "0":
                                                meterData.setAnalysis("==");
                                                break;
                                            case "1":
                                                meterData.setAnalysis("★");
                                                break;
                                            case "2":
                                                meterData.setAnalysis("★★");
                                                break;
                                            case "3":
                                                meterData.setAnalysis("★★★");
                                                break;
                                        }

                                    });
                                    if (first) {
                                        smartTable.setData(meterDataLists);
                                        first = false;
                                    } else {
                                        smartTable.addData(meterDataLists, true);
                                        smartRefreshLayout.finishLoadMore();

                                    }
                                }
                            }

                            Toast.makeText(DataInfoActivity.this, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                            if (jsonObject.getInt("code") == 1) {

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onAfter(int id) {
                        super.onAfter(id);
                        smartRefreshLayout.finishRefresh(true);
                        dialog.dismiss();
                    }
                });


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;

            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}